package uf.audit.util;

import com.google.code.kaptcha.servlet.KaptchaServlet;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.piaohao.fast.jfinal.IServerInvoke;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Enumeration;
import java.util.Properties;

public class KaptchaSupport implements IServerInvoke {

    public void invoke(Tomcat tomcat, Context currentContext) throws ServletException {
        final Properties properties = new Properties();
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
        properties.setProperty("kaptcha.image.width", "100");
        properties.setProperty("kaptcha.image.height", "37");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.size", "25");
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        final KaptchaServlet kServlet = new KaptchaServlet();
        ServletConfig config = new ServletConfig() {

            public String getServletName() {
                return kServlet.getServletName();
            }

            public ServletContext getServletContext() {
                return kServlet.getServletContext();
            }

            public String getInitParameter(String name) {
                return (String) properties.get(name);
            }

            public Enumeration<String> getInitParameterNames() {
                return (Enumeration<String>) properties.propertyNames();
            }
        };
        kServlet.init(config);
        tomcat.addServlet(currentContext.getPath(), "Kaptcha", kServlet);
        currentContext.addServletMappingDecoded("/jym.jpg", "Kaptcha");
    }
}
